package com.wzh.project.utils.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.wzh.project.utils.ssh2.SSHUtil;
import com.wzh.project.utils.ssh2.SshConfiguration;

/**
*@author : 汪振海
*@createdDate : Jan 17, 2020  10:37:28 AM
*@description : 读取文件内容<br>
*
*/
public class FileContentUtil {
	
	
	private static final Logger logger = LogManager.getLogger(FileContentUtil.class);
	
	private static String path ="/home/k8s/share/data/logs/nsso/nsso-7656f4b44f-msxhd/tlogs/";
	
	private static String logName="sword.log";
	
	private String sqlKeyName="MH004_searchYyuuidByYhuuid";
	
	private String outFileName="wzh_sql2.out";
	
	private String cmd1="cat "+logName+" |grep -A 2  "+sqlKeyName+" > "+outFileName;
	
	
	private static String str1="cat sword-2.log |grep -A 2  MH004_searchYyuuidByYhuuid > wzh_sql2.out";
	
	
	String startString="调用参数:";
	String subString="请求ID:";
	
	public static String regex="^调用参数:.*请求ID:.*$";
	
	
	public static void main2(String[] args) throws Exception {
		String str="调用参数:[f5d9e73707e84c25b1d531d8f3689f18]，请求ID:1ffa58b2\r\n" + 
				"2020-01-17 10:19:30,787|TID: N/A|DEBUG|DBTracer|1076b82909d245f3be84790c29327fac|11526250024|313|1|成功执行请求1ffa58b2，执行时间(ms):1，结果集记录数:2条\r\n" + 
				"调用参数:[8c87839fc20a48c999a4658265583434]，请求ID:182f0494\r\n" + 
				"2020-01-17 10:19:30,790|TID: N/A|DEBUG|DBTracer|34e2af12846a400591f9462285de9735|11501000056|408|1|成功执行请求182f0494，执行时间(ms):2，结果集记录数:2条\r\n" + 
				"调用参数:[a258a43af9844b1aa9963fa8e86662bf]，请求ID:41eb5dc8\r\n" + 
				"2020-01-17 10:19:30,792|TID: N/A|DEBUG|DBTracer|d018a2613bec4083ae21268dbb617623|11501040021|286|1|成功执行请求41eb5dc8，执行时间(ms):3，结果集记录数:1条\r\n" + 
				"调用参数:[f90befd94e5d4475beaa8a450459e372]，请求ID:3a4d856e\r\n" + 
				"2020-01-17 10:19:30,794|TID: N/A|DEBUG|DBTracer|e0d16dfee4c84028a0b6b30fd2828d99|null|381|1|成功执行请求3a4d856e，执行时间(ms):4，结果集记录数:2条\r\n" + 
				"";
		String tt4=str.substring(str.lastIndexOf("执行时间(ms):")+9, str.lastIndexOf("，结果集记录数"));
		str=str.substring(0,str.lastIndexOf("调用参数:"));
		String tt3=str.substring(str.lastIndexOf("执行时间(ms):")+9, str.lastIndexOf("，结果集记录数"));
		str=str.substring(0,str.lastIndexOf("调用参数:"));
		String tt2=str.substring(str.lastIndexOf("执行时间(ms):")+9, str.lastIndexOf("，结果集记录数"));
		str=str.substring(0,str.lastIndexOf("调用参数:"));
		String tt1=str.substring(str.lastIndexOf("执行时间(ms):")+9, str.lastIndexOf("，结果集记录数"));
		str=str.substring(0,str.lastIndexOf("调用参数:"));
		System.out.println(tt4);
//		test();
	}
	
	//处理批量sql
	public static void dealpatchString(List<Long> list,String tmp) {
		String str=new String(tmp);
		while(str!=null&&"".equals(str)) {
			String value=str.substring(str.lastIndexOf("执行时间(ms):")+9, str.lastIndexOf("，结果集记录数"));
			str=str.substring(0,str.lastIndexOf("调用参数:"));
			list.add(Long.valueOf(value));
		}
	}
	
	public static void test() throws Exception{
		SshConfiguration conf=new SshConfiguration();
		String host="172.16.4.7";
		String userName="root";
		String password="654Root321";
		conf.setHost(host);
		conf.setUsername(userName);
		conf.setPassword(password);
		conf.setPort(22);
		SSHUtil ssh=new SSHUtil(conf);
		String cmd="cat /home/k8s/share/data/logs/mhpt/mhpt-fbb87f95f-ncz6g/tlogs/sword.log |grep 1ffa58b2"+" && "+
				"cat /home/k8s/share/data/logs/mhpt/mhpt-fbb87f95f-ncz6g/tlogs/sword.log |grep 41eb5dc8";
		String result=ssh.runCmd(cmd, "utf-8");
		System.out.println(result);
	}
	
	
	/**
	 * 筛选数据
	 */
	public static void screenDate() {
		
	}
	
	public static void main(String[] args) throws Exception {
		
//		String temp="2020-01-17 10:17:27,589|TID: N/A|DEBUG|DBTracer|d8ce8dc55fa4434f919690f7d2ff8894|null|273|1|成功执行请求506710a8，执行时间(ms):1，结果集记录数:1条";
//		int indexOf = temp.indexOf("成功执行请求506710a8，执行时间(ms):");
//		int endIndex=temp.lastIndexOf("，结果集记录数:");
//		String substring2 = temp.substring(indexOf+6+8+10, endIndex);
		//提取文件中所有的连接id
		List<String> ids = getDataConnectIds("C:\\Users\\wzh\\Desktop\\sql.out");
		if (ids==null||ids.size()==0) {
			return ;
		}
				
		SshConfiguration conf=new SshConfiguration();
		String host="172.16.4.7";
		String userName="root";
		String password="654Root321";
		conf.setHost(host);
		conf.setUsername(userName);
		conf.setPassword(password);
		conf.setPort(22);
		SSHUtil ssh=new SSHUtil(conf);
		//执行提取文件
//		ssh.runCommondNoResult(str1);
		List<String> patchlistres=new ArrayList<String>();//用于保存执行批量执行cat命令结果
		List<String> listres=new ArrayList<String>();//用于保存执行批量执行cat命令结果
		long resultLong=0;//用于保存平均值
//		String cmd="cd /home/k8s/share/data/logs/mhpt/mhpt-fbb87f95f-ncz6g/tlogs \r\n";
		String cmd="cd "+path+" ";
		int count=0;
		int num=0;
		for (String id : ids) {
			if (num>100) {
				break;
			}
			//拼接一下linux命令
			cmd+=" && "+" cat "+logName+" |grep "+id;
			count++;
			if (count>=5) {
				//50 条命令执行一次
				String res=ssh.runCmd(cmd, "utf-8");
				logger.debug(res);
				if (res!=null&&!"".equals(res)) {
					patchlistres.add(res);
				}
				count=0;
				cmd="cd "+path+" ";
			}
		}
		//最后的结果//如果想要输出所有的日志可以考虑输出到文件中
		List<Long> result=new ArrayList<Long>();
		//把批量转为单个放入list中
		for (int i = 0; i < patchlistres.size(); i++) {
			dealpatchString(result, patchlistres.get(i));
		}
		
		for (int i = 0; i < result.size(); i++) {
			resultLong+=resultLong+result.get(i);
			System.out.println("耗费时间为:");
		}
		long avg=resultLong/result.size();
		System.out.println("平均时间为:"+avg);
	}
	
	 public static List<String> getDataConnectIds(String filePath) throws Exception {
	        FileReader fileReader = new FileReader(filePath);
	        BufferedReader reader = new BufferedReader(fileReader);
	        String s = reader.readLine();
	        List<String> list = new ArrayList<>();
	        while (s != null) {
	        	Pattern r = Pattern.compile(regex);
	    		Matcher m = r.matcher(s);
	        	if (m.find()) {
					//说明是满足要求的时间
	        		list.add(s.substring(s.lastIndexOf("请求ID:") + 5));
				}
	            s = reader.readLine();
	        }
	        return list;
	    }
	
	

}
